package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.mapper.NurseLeaveMapper;
import com.ruoyi.system.domain.NurseLeave;
import com.ruoyi.system.service.INurseLeaveService;
import com.ruoyi.system.service.ISysMessageService;
import com.ruoyi.system.domain.SysMessage;

/**
 * 护理人员请假Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class NurseLeaveServiceImpl implements INurseLeaveService
{
    @Autowired
    private NurseLeaveMapper nurseLeaveMapper;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysMessageService messageService;

    /**
     * 查询护理人员请假
     * 
     * @param leaveId 护理人员请假主键
     * @return 护理人员请假
     */
    @Override
    public NurseLeave selectNurseLeaveByLeaveId(Long leaveId)
    {
        return nurseLeaveMapper.selectNurseLeaveByLeaveId(leaveId);
    }

    /**
     * 查询护理人员请假列表
     * 
     * @param nurseLeave 护理人员请假
     * @return 护理人员请假
     */
    @Override
    public List<NurseLeave> selectNurseLeaveList(NurseLeave nurseLeave)
    {
        return nurseLeaveMapper.selectNurseLeaveList(nurseLeave);
    }

    /**
     * 新增护理人员请假
     * 
     * @param nurseLeave 护理人员请假
     * @return 结果
     */
    @Override
    @Transactional
    public int insertNurseLeave(NurseLeave nurseLeave)
    {
        // 获取当前登录用户信息
        Long userId = SecurityUtils.getUserId();
        // 判断角色是否为护理人员
        if (!SecurityUtils.hasRole("nurse"))
        {
            throw new ServiceException("只有护理人员可以申请请假");
        }
        
        SysUser user = userService.selectUserById(userId);
        if (user == null)
        {
            throw new ServiceException("用户不存在");
        }
        
        // 设置护理人员ID和姓名
        nurseLeave.setNurseId(userId);
        nurseLeave.setNurseName(user.getNickName());
        nurseLeave.setCreateTime(DateUtils.getNowDate());
        nurseLeave.setStatus("0"); // 待审核
        nurseLeave.setDelFlag("0");
        
        // 设置请假状态
        SysUser updateUser = new SysUser();
        updateUser.setUserId(userId);
        updateUser.setLeaveStatus("1"); // 请假中
        userService.updateUser(updateUser);
        
        int rows = nurseLeaveMapper.insertNurseLeave(nurseLeave);
        
        // 添加新代码：发送通知给HR角色的用户
        if (rows > 0) {
            try {
                // 获取所有具有人事角色(roleId=103)的用户
                List<SysUser> hrUsers = userService.selectUserListByRoleId(103L);

                for (SysUser hr : hrUsers) {
                    SysMessage message = new SysMessage();
                    message.setTitle("护士请假申请通知");
                    message.setContent("护士 " + user.getNickName() + " 提交了请假申请，请尽快审核。请到【护士请假审核】菜单进行处理。");
                    message.setMessageType("1"); // 系统通知
                    message.setReceiverId(hr.getUserId()); // 发送给用户ID=1 (通常是管理员)
                    message.setReceiverType("3"); // 接收者类型
                    
                    // 尝试发送消息
                    messageService.insertSysMessage(message);
                }
            } catch (Exception e) {
                // 捕获异常，确保即使消息发送失败，请假申请仍能正常保存
                System.out.println("发送请假审核通知失败：" + e.getMessage());
            }
        }
        
        return rows;
    }

    /**
     * 修改护理人员请假
     * 
     * @param nurseLeave 护理人员请假
     * @return 结果
     */
    @Override
    public int updateNurseLeave(NurseLeave nurseLeave)
    {
        nurseLeave.setUpdateTime(DateUtils.getNowDate());
        return nurseLeaveMapper.updateNurseLeave(nurseLeave);
    }

    /**
     * 批量删除护理人员请假
     * 
     * @param leaveIds 需要删除的护理人员请假主键
     * @return 结果
     */
    @Override
    public int deleteNurseLeaveByLeaveIds(Long[] leaveIds)
    {
        return nurseLeaveMapper.deleteNurseLeaveByLeaveIds(leaveIds);
    }

    /**
     * 删除护理人员请假信息
     * 
     * @param leaveId 护理人员请假主键
     * @return 结果
     */
    @Override
    public int deleteNurseLeaveByLeaveId(Long leaveId)
    {
        return nurseLeaveMapper.deleteNurseLeaveByLeaveId(leaveId);
    }
    
    /**
     * 审核护理人员请假
     * 
     * @param leaveId 请假ID
     * @param status 审核状态
     * @param auditRemark 审核备注
     * @return 结果
     */
    @Override
    @Transactional
    public int auditNurseLeave(Long leaveId, String status, String auditRemark)
    {
        // 校验参数
        if (leaveId == null)
        {
            throw new ServiceException("请假ID不能为空");
        }
        if (status == null || (!status.equals("1") && !status.equals("2")))
        {
            throw new ServiceException("审核状态不正确");
        }
        
        // 查询请假记录
        NurseLeave nurseLeave = nurseLeaveMapper.selectNurseLeaveByLeaveId(leaveId);
        if (nurseLeave == null)
        {
            throw new ServiceException("请假记录不存在");
        }
        
        // 只能审核待审核状态的请假
        if (!"0".equals(nurseLeave.getStatus()))
        {
            throw new ServiceException("该请假记录已审核");
        }
        
        // 更新请假记录
        NurseLeave updateLeave = new NurseLeave();
        updateLeave.setLeaveId(leaveId);
        updateLeave.setStatus(status);
        updateLeave.setAuditBy(SecurityUtils.getUsername());
        updateLeave.setAuditTime(new Date());
        updateLeave.setAuditRemark(auditRemark);
        
        // 如果是拒绝请假，需要更新护理人员的请假状态
        if ("2".equals(status))
        {
            SysUser updateUser = new SysUser();
            updateUser.setUserId(nurseLeave.getNurseId());
            updateUser.setLeaveStatus("0"); // 不在请假中
            userService.updateUser(updateUser);
        }
        
        return nurseLeaveMapper.updateNurseLeave(updateLeave);
    }
} 